#include <iostream>
#include <string>
#include <string.h>
#include <fstream>
#include <sys/stat.h>
using std::cout;
using std::endl;
using std::string;
using std::ios;


long getSize(FILE *name)
{
	long currentPos;
	long endPos;
	
	currentPos = ftell(name);
	//Sets the position to the end of the file
	fseek(name, 0, SEEK_END);
	endPos = ftell(name);
	fseek(name, currentPos, 0);
	
	
	return endPos;
}

bool fileExists(const string& name)
{
	struct stat u;
	if(stat(name.c_str(), &u) != -1)
	{
		return true;
	}
	return false;
}

int main(int argv, char *argc[])
{
	int n;
	unsigned char *fileBuf;
	FILE *bml5 = NULL;
	long size;
	unsigned char code[] = "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x30\x30\x30\x30\x30\x30\x30\x30";
	long currentPosition;
	
	//Check if the file exists
	if(fileExists("bml5.img"))
	{
		cout << "->bml5.img exists on the system" << endl;
	}
	
	//Open the file
	if((bml5 = fopen("bml5.img", "rb")) != NULL)
	{
		size = getSize(bml5);
		cout << "->bml5.img opened successfully" << endl;
		cout << "->bml5.img is " << size << " bytes long" << endl;
		cout << "->code to compare is " << sizeof(code) - 1 << " bytes long" << endl;
	}
	
	//Create a new array with enough buffer
	fileBuf = new unsigned char[size];
	//Read the file
	fread(fileBuf, size, 1, bml5);
	//Get the current position of the pointer
	currentPosition = ftell(bml5);
	//Back to the original position
	rewind(bml5);
	//Update the current position
	currentPosition = ftell(bml5);
	
	for(int i = 0; i < size; i += 0x1)
	{
		cout.unsetf(ios::dec);
		cout.setf(ios::hex | ios::showbase);
		//Compare each segment with the next 32 bytes and code array
		n = memcmp(&fileBuf[i], code, 32);
		
		if(n == 0 && (isdigit(fileBuf[i - 0x1])))
		{
			if(!(fileBuf[i - 0x1] == '0' && fileBuf[i - 0x2] == '0' && fileBuf[i - 0x3] == '0' && fileBuf[i - 0x4] == '0' &&
			fileBuf[i - 0x5] == '0' && fileBuf[i - 0x6] == '0' && fileBuf[i - 0x6] == '0' && fileBuf[i - 0x7] == '0' && 
			fileBuf[i - 0x8] == '0'))
			{
				cout << "[CODE FOUND]";
				for(int l = 0x8; l > 0; l -= 0x1)
				{
					cout << fileBuf[i - l];
				}
				cout << endl;
			}
		}
	}
	
	
	delete[] fileBuf;
	fclose(bml5);
	
	return 0;
}
